﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sunboxsoft.ASMS.Server.Domain.Threads
{
    /// <summary>
    /// 日结线程
    /// </summary>
    class DialySettleThread
    {
        static List<DialySettleThread> s_thread = new List<DialySettleThread>();

        public static Guid Start(Guid businessId, Guid stationId, DateTime date)
        {
            for (int index = 0; index < s_thread.Count; index++)
            {
                if(s_thread[index].BusinessId == businessId && s_thread[index].StationId == stationId && s_thread[index].Date == date)
                {
                    return s_thread[index].Id;
                }
            }

            DialySettleThread thread = new DialySettleThread(Guid.NewGuid(), businessId, stationId, date);
            s_thread.Add(thread);
            return thread.Id;
        }

        public static bool QueryProgress(Guid id)
        {
            for (int index = 0; index < s_thread.Count; index++)
            {
                if (s_thread[index].Id == id)
                {
                    return s_thread[index].IsFinished;
                }
            }
            return true;
        }

        public static void Finished(Guid id)
        {
            for (int index = 0; index < s_thread.Count; index++)
            {
                if (s_thread[index].Id == id)
                {
                    if (s_thread[index].IsFinished)
                    {
                        s_thread.RemoveAt(index);
                        break;
                    }
                }
            }
            return;
        }

        public Guid Id { get; set; }
        public Guid BusinessId{get;set;}
        public Guid StationId { get; set; }
        public DateTime Date { get; set; }
        public bool IsFinished { get; set; }

        public Thread _thread;

        public DialySettleThread(Guid id, Guid businessId, Guid stationId, DateTime date)
        {
            this.Id = id;
            this.BusinessId = businessId;
            this.StationId = stationId;
            this.Date = date;
            this.IsFinished = false;
        }

        public void Start()
        {
            _thread = new Thread(Running);
            _thread.Start();
        }

        public void Running()
        {
            using(ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EDailySettlement settlement = new Entity.EDailySettlement();
                settlement.Id = Guid.NewGuid();
                //settlement.MaintenanceBillCount = dbContext.set
            }
        }
    }
}
